/**
 * Created by shandianhaizan on 16/6/16.
 */

define([], function () {

    function _controller($scope, $routeParams, $location, $timeout, httpService) {

        var id = $routeParams.id;
        var model ="Production";
        $scope.properties = [];
        $scope.classifications = [];
        $scope.classificationObject = {};

        var isUpdate = function(){
            return id && id!=="new"
        };


        var inArray = function(one, arr){
            return $.inArray(one, arr)>=0
        };
        var inProperty = function(one , arr){
            for(var i= 0, l=arr.length; i<l; i++){
                if(one.name == arr[i].key){
                    return true;
                }
            }
            return false;
        };
        var inRelation = function(one , arr){
            for(var i= 0, l=arr.length; i<l; i++){
                if(one.objectId == arr[i].objectId){
                    return true;
                }
            }
            return false;
        };


        $scope.toggle = function (scope) {
            scope.toggle();
        };

        //判断列表树的分类是否已经存在
        $scope.checkCp = function(node){
            return inArray(node.objectId, $scope.production.classification || []);
        };

        $scope.handleCCheck = function(node, bool){
            if(bool){
                $scope.addClass(node.objectId);
            }else{
                $scope.remove(node.objectId, $scope.production.classification);
            }

        };


        //初始化属性
        $scope.initProperty = function () {
            httpService.get("Property", {all:true}).then(function (data) {
                $scope.properties = data.data.data;
            });
        };



        $scope.formatData = function (datas){
            var tmpObject = {};
            var tmpData = [];
            angular.forEach(datas, function(data){
                tmpObject[data.objectId] = data;
                if (data.pid && data.pid!=="0"){
                    var parent = tmpObject[data.pid];
                    if(parent){
                        parent.nodes = parent.nodes || [];
                        parent.nodes.push(data);
                    }
                }else{
                    tmpData.push(data);
                }
            });
            $scope.classifications = tmpData;
        };

        //初始化分类
        $scope.initClassification = function () {
            httpService.get("Classification", {all:true}).then(function (data) {
                $scope.classifications = data.data.data;
                angular.forEach($scope.classifications, function(c){
                    $scope.classificationObject[c.objectId] = c;
                });
                $scope.formatData($scope.classifications);
            });
        };




        //添加分类
        $scope.addClass = function(c){
          if(!c || inArray(c, $scope.production.classification)) return;
          $scope.production.classification =   $scope.production.classification || [];
          $scope.production.classification.push(c);
        };


        //添加属性组
        $scope.addPropertyGroup = function(c){
            if(!c) return;
            $scope.production.properties =   $scope.production.properties || [];
            angular.forEach($scope.properties, function(p){
                if(p.type == '0' && p.pid == c.objectId && !inProperty(p,$scope.production.properties)) {
                    $scope.production.properties.push({key: p.name});
                }
            })
        };


        //添加属性
        $scope.addProperty = function(c){
            if(!c) return;
            $scope.production.properties =   $scope.production.properties || [];
            c = {name:c};
            if(!inProperty(c, $scope.production.properties)) {
                $scope.production.properties.push({key: c.name});
            }

        };

        $scope.addRelation = function(c){
            if(!c || !c.objectId) return;
            $scope.production.relation =   $scope.production.relation || [];
            if(!inRelation(c, $scope.production.relation)) {
                $scope.production.relation.push({objectId: c.objectId, name: c.name});
            }

        };


        $scope.addTags = function(t){
            if(!t) return;
            $scope.production.tags =   $scope.production.tags || [];
            if(!inArray(t, $scope.production.tags)) {
                $scope.production.tags.push(t);
            }

        };

        $scope.remove = function(one, arr){
            arr.splice( $.inArray(one, arr), 1);
        };






        $scope.appendImg = function (url) {
            if (!url) return;
            $scope.production.images =$scope.production.images ||[];
            $scope.production.images.push(url);
        };


        $scope.galleryConfig = {
            animation: 300,
            onUpdate: function (/**Event*/evt) {
            }
        };

        $scope.options = {
            language: 'zh-cn',
            allowedContent: true,
            entities: false
        };

        // Called when the editor is completely ready.
        $scope.onReady = function () {
        };


        $scope.addSku = function () {
            $scope.production.skus =   $scope.production.skus|| [];
            $scope.production.skus.push({name: "", spec: [{name:""}]});
        };



       $scope.evalSkuDetail = function (A){

           var production =  $scope.production;

           //保存现场
           $scope.orginSkuDetail = {};
           angular.forEach(production.skuDetail,function(d){
               if(d.name){
                   $scope.orginSkuDetail[d.name] = d;
               }
           });

           $scope.production.skuDetail = [];
           var script = "inner";
           for (var i = 0, l = A.length; i < l; i++) {
               var inner;
               inner = 'for(var i' + i + '=0, l' + i + '= A[' + i + '].length; i' + i + '<l' + i + '; i' + i + '++){' +
                   'inner' +
                   '}';

               script = script.replace("inner", inner);
           }

           var i = 0, AN = 'A', stop = '';
           while (i < A.length) {
               if (!stop) {
                   stop = AN + '[' + i + '][i' + i + ']';
               } else {
                   stop = stop + '+"*"+' + AN + '[' + i + '][i' + i + ']';
               }
               i++;
           }
           stop = '$scope.production.skuDetail.push({name:' + stop + '})';
           script = script.replace("inner", stop);
           eval(script);

           //恢复现场
           angular.forEach(production.skuDetail, function(d, i){
               if(d.name && $scope.orginSkuDetail[d.name]){
                   production.skuDetail[i] = $scope.orginSkuDetail[d.name];
               }
           });
       };


        $scope.generateSkuDetail = function(){
            var A =[];
            angular.forEach($scope.production.skus, function(sku){
                var B = [];
                angular.forEach(sku.spec, function(spec){
                   B.push(spec.name);
                });
                A.push(B);
            });
            $scope.evalSkuDetail(A);
        };

        $scope.addSkuSpec = function (spec) {
            spec.push({name:""});
        };


        $scope.save = function () {
            $scope.$broadcast('show-errors-check-validity');
            if (!$scope.userForm.$valid) return;
            httpService.save(model, $scope.production).then(function (data) {
                $scope.msg.show(data);
                 if($scope.isHandleSuccess(data) && !isUpdate()){
                     $location.path('/edit-production/'+data.data.objectId);
                 }
            });

        };


        $scope.searchProduction = function (keyword) {
           return httpService.get("Production",{name:keyword});
        };


        $scope.appendSkuImg = function(url, sku){
            sku.img = url;
        };


        $scope.reset = function () {
            $scope.$broadcast('show-errors-reset');
            $scope.production = {};
        };



        if(isUpdate()){
            httpService.get(model, id).then(function (data) {
                $scope.production = data.data;
                $scope.initClassification();
                $scope.initProperty();
            });
        }else{
            $scope.initClassification();
            $scope.initProperty();
            $scope.production = {
                skus: [{name: "", spec: [{name:""}]}],
                skuDetail: [],
                images: ["http://7xo1cv.com1.z0.glb.clouddn.com/Fh0EJEDTkZbqBK1nY0JCybq1pcPV"]
            };
        }


    }

    return _controller;
});



